package cn.xaut.春招2021;

import cn.xaut.剑指offer.m20.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 */
public class demo105 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) 
            map.put(inorder[i], i);

        return buildTree(preorder, 0, preorder.length - 1, map, inorder, 0, inorder.length);
    }

    public TreeNode buildTree(int[] preorder, int preLeft, int preRight, Map<Integer, Integer> map, int[] inorder, int inLeft, int inRight) {
        
        if (preLeft > preRight || inLeft > inRight)
            return null;

        int rootVal = preorder[preLeft];
        TreeNode root = new TreeNode(rootVal);
        int pIndex = map.get(rootVal);

        root.left = buildTree(preorder, preLeft + 1, pIndex - inLeft + preLeft, map, inorder, inLeft, pIndex - 1);
        root.right = buildTree(preorder, pIndex - inLeft + preLeft + 1, preRight, map, inorder, pIndex + 1, inRight);
        
        return root;
    }
    
}
